<?php

class User_Form_RegisterCompanyForm extends Ac_Form
{

    /**
     *
     * @var Model_User empty user with properly setted behavior
     */
    private $_user;

    protected $elementButtonDecorators = array(
        'ViewHelper',
        'Errors',
    );

    protected $elementDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'p')),
    );

    protected $elementType = array(
        'ViewHelper',
        'Errors',
        );

    protected $formDecorators = array(
        'FormElements',
        array('Description', array('placement' => 'prepend')),
        'Form'
    );

    protected $subFormDecorators = array(
        'FormElements',
        array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'section', 'class' => 'intro')),
        'fieldset',
    );

    protected $spanDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array('placement' => 'prepend')),
        array(array('row' => 'HtmlTag'), array('tag' => 'span')),
    );

    protected $displayGroupDecorators = array(
        'FormElements',
    );

    protected $elementSelectDecorators = array(
        'ViewHelper',
        'Errors',
        array('Label', array()),
        array(array('row' => 'HtmlTag'), array('class'=>'select')),
    );

    function setUser($user)
    {
        $this->_user = $user;
    }

    
    /**
     * define form elements
     */
    public function init()
    {
        parent::init();

        $this->setMethod('post');
        $this->setAction($this->getView()->geturl('register-company' ,'user'));
        $this->setAttrib('style', 'margin : 0px 0px');
        $this->initCompanyInfo();
        $this->initPersonalInfo();
        
    }

    private function initCompanyInfo()
    {
        $form = $this->getNewSubForm();
        $form->setDecorators($this->subFormDecorators);

        /* Company Name (username) */
        $form->addElement('text', 'company_name', array(
            'description' => '4-30个字符',
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('StringLength', true, array(4, 30, 'messages' => '4-30个字符')),
            ),
            'decorators' => array(
                'ViewHelper',
                'Errors',
                array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                array('Label', array('placement' => 'prepend')),
                array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'signup_company text')),
            ),
            'required'   => true,
            'label'      => 'Company Name (Username)',
        ));

        /* phone */
        $form->addElement('text', 'company_phone', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'description' => 'Primary contact number for your company',
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('int', false, array('messages' => array(Zend_Validate_Int::NOT_INT =>'Numbers only'))),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'phone_company text')),
            ),
            'required'   => true,
            'label'      => 'Company Phone',
        ));

        // Business Category
        $form->addElement('select', 'business_category', array(
            //'filters'    => array('StringTrim'),
            'validators' => array(
                 array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators'   => $this->elementSelectDecorators,
            'multiOptions' => Model_Company::getBusinessCategory(),
            'required'     => true,
            'label'      => 'Business Category',
        ));

        /*mailling address */
        $form->addElement('textarea', 'company_mail_address', array(
            'filters'    => array('StringTrim'),
            'label'      => 'Mailling Address (optional)',
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Label', array('placement' => 'prepend', 'class' => 'address textarea')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'address textarea')),
            )
        ));

        /* Company Website */
        $form->addElement('text', 'company_website', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'username text')),
            ),
            'label'      => 'Company Website (optional)',
        ));

        $view = Zend_Registry::get('Zend_View');
        $form->getErrors();
        $form->setLegend('Company Information');
        $form->setDescription($view->t('
            <h3>Company Accounts</h3>
            <ul>
                <li>Are specially designed to promote businesses</li>
                <li>Auto-list your Company details in AsiaClassified\'s Business Directory - Free</li>
                <li>Allows you designate Sub-Accounts for your sales team</li>
                <li>Provide consolidated reports across all accounts (Primary and Subs)</li>
            </ul>')
        );
        $form->addDecorator('fieldset');
        $this->addSubForm($form, 'newaccount');

        //$this->addDisplayGroup(array('company_name', 'company_phone', 'company_mail_address', 'company_website'), 'company', array('legend'=>'Company Information'));
    }

    private function initPersonalInfo()
    {
        $form = $this->getNewSubForm();
        $form->setDecorators($this->subFormDecorators);

        /* First name */
        $form->addElement('text', 'firstname', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'p', 'class' => 'first_name text')),
            ),
            'required'   => true,
            'label'      => 'First Name',
        ));

        /* Lastname */
        $form->addElement('text', 'lastname', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'last_name text')),
            ),
            'required'   => true,
            'label'      => 'Last Name',
        ));

        /* Username */
        /*$form->addElement('text', 'username', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'description' => '4 - 12 characters',
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('StringLength', true, array(4, 12, 'messages' => '4-12 characters limit')),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'last_name text')),
            ),
            'required'   => true,
            'label'      => 'Username',
        ));*/

        /* Email */
        $form->addElement('text', 'email', array(
            'filters'    => array('StringTrim'),
            'description' => "Don't worry we won't spam you",
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('EmailAddress', true, array('messages' => array(Zend_Validate_EmailAddress::INVALID_FORMAT => 'Valid email required'))),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'email text')),
            ),
            'required'   => true,
            'label'      => 'Email Address',
        ));

        /* Confirm email */
        $form->addElement('text', 'confirm_email', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'email_confirm text')),
            ),
            'required'   => true,
            'label'      => 'Confirm Email Address',
        ));


        /* Phone */
        $form->addElement('text', 'phone', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('int', false, array('messages' => array(Zend_Validate_Int::NOT_INT =>'Numbers only'))),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'mobile text')),
            ),
            'required'   => false,
            'label'      => 'Mobile (Optional)',
        ));


        /* Password */
        $form->addElement('password', 'password', array(
            'filters'    => array('StringTrim'),
            'description' => '6-20 characters, no space',
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
                array('StringLength', true, array(6, 20, 'messages' => '6-20 characters limit')),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'password text')),
            ),
            'required'   => true,
            'label'      => 'Password',
        ));

        /* Confirm password */
        $form->addElement('password', 'confirm_password', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('NotEmpty', true, array('messages' => 'This information is required')),
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array('Description', array('escape' => false, 'placement' => 'PREPEND', 'tag' => 'span', 'class' => '')),
                            array('Label', array('placement' => 'prepend')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'password_confirm text')),
            ),
            'required'   => true,
            'label'      => 'Confirm password',
        ));

        /* Captcha */
        $form->addElement('captcha', 'captcha',
                array('label' => 'Validation Code',
                'captcha' => array( // Here comes the magic...
                    // First the type...
                    'captcha' => 'Image',
                    // Length of the word...
                    'wordLen' => 6,
                    // Captcha timeout, 5 mins
                    'timeout' => 300,
                    // What font to use...
                    'font' => PUBLIC_PATH.'/images/captcha/verdana.ttf',
                    // Where to put the image
                    'imgDir' => PUBLIC_PATH.'/images/captcha/',
                    // URL to the images
                    // This was bogus, here's how it should be... Sorry again :S
                    //'imgUrl' => 'http://project.com/captcha/',
                    'lineNoiseLevel' => 0,
                    'dotNoiseLevel' => 50,
                ),
                'validators' => array(
                    array('NotEmpty', true, array('messages' => 'This information is required')),
                ),
                'decorators' => array(
                    'Errors',
                    array('Label', array('placement' => 'prepend')),
                    array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'validation text')),
                ),
            )
        );

        $form
            ->getElement('captcha')
            ->getValidator('Zend_Captcha_Image')
            ->setMessage('This Information is required', Zend_Captcha_Word::MISSING_VALUE)
            ->setMessage('Invalid Validation Code', Zend_Captcha_Word::BAD_CAPTCHA);
             
        /* Newsletter */
        $form->addElement('checkbox', 'newsletter', array(
            'filters'    => array('StringTrim'),
            'description' => '<br><h4 class="remark">By clicking Create My Account, you agree to AsiaClassified’s <a href="/default/index/term-of-use">Terms of Use</a> and <a href="/default/index/privacy">Privacy Policy</a>.</h4>',
            'validators' => array(
            ),
            'decorators' => array(
                            'ViewHelper',
                            'Errors',                            
                            array('Label', array('placement' => 'APPEND')),
                            array('Description', array('escape' => false, 'placement' => 'APPEND', 'tag' => 'div', 'class' => 'remark')),
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'newsletter checkbox')),
            ),
            'value' => '1',
            'label'      => 'I would like to receive the AsiaClassified Newsletter'
        ));

        $form->addElement('hidden', 'type', array(
            'validators' => array(
                'Alpha',
            ),            
            'value' => 'company',
            'required'   => true,
        ));
        $form->getElement('type')->removeDecorator('label');

        /* Submit Button */
        $form->addElement('button', 'register', array(
            'required' => false,
            'ignore'   => true,
            'label'       => 'Create My Account',
            'decorators' => array(
                            'ViewHelper',
                            'Errors',
                            array(array('row' => 'HtmlTag'), array('tag' => 'div', 'class' => 'button_em')),
            ),
            'type'        => 'submit',
        ));

        $form->getErrors();
        $form->setLegend('Primary Account Owner Information');
        $view = Zend_Registry::get('Zend_View');
        $form->setDescription(
            $view->t('<h3>Primary Administrative Account</h3>
            <p>
                This is the Primary Administrative Account for your company. Once you have created your account you can add, remove and monitor assigned Sub-Accounts.
            </p>
            <h3>Sub-Accounts:</h3>
            <ul>
                <li>Are specially designed for sales teams and sales agents</li>
                <li>Allow more than one person to create, post and manage their Ads within one Company Account</li>
            </ul>')
        );
        $form->addDecorator('fieldset');
        $this->addSubForm($form, 'personal');

        //$this->getElement('newsletter')->addDecorator('Label', array('placement' => 'APPEND'));
        
        //$this->addDisplayGroup(array('firstname', 'lastname', 'email', 'confirm_email', 'phone', 'password', 'confirm_password', 'captcha', 'newsletter'), 'personal', array('legend'=>'Main Account Information'));
    }
    
    public function isValidPartial(array $post = array())
    {
        $test = parent::isValidPartial($post);
        return $this->validate($post) & $test;
    }
    /**
     *
     * @param array $post
     */
    public function isValid($post = array())
    {
        $test = parent::isValid($post);
        return $this->validate($post) & $test;
    }
    
    /**
     *
     * @param array $post
     */
    public function validate($post = array())
    {
        
        $test = true;
        
        //TODO: check if email and confirm emails are the same
        if ((!empty($post['personal']['email'])) &&  (!empty($post['personal']['confirm_email']))) {
            $email = $post['personal']['email'];
            $confirm_email = $post['personal']['confirm_email'];
            if (trim($email) != trim($confirm_email)) {
                $this->getSubForm('personal')->getElement('confirm_email')->addError('Emails do not match');
                $test = false;
            }
        }
        //TODO: check if email exists
        if (!empty($post['personal']['email'])) {
            $num = Model_User::one(array('email' => $post['personal']['email']));
            if (!empty($num)) {
                $this->getSubForm('personal')->getElement('email')->addError($post['personal']['email'].' is already taken');
                $test = false;
            }
        }

        //TODO: check if company exists
        if (!empty($post['newaccount']['company_name'])) {
            $num = Model_Company::one(array('username' => $post['newaccount']['company_name']));
            if (!empty($num)) {
                $this->getSubForm('newaccount')->getElement('company_name')->addError($post['newaccount']['company_name'].' is already taken');
                $test = false;
            }
        }

        //TODO: check the password
        $password = $post['personal']['password'];
        $confirm_password = $post['personal']['confirm_password'];
        if ((strlen($password) >= 6) && (strlen($password) <= 20)) {
            // The password is long enough we can check it with confirm password
            if (trim($password) != trim($confirm_password)) {
                $this->getSubForm('personal')->getElement('confirm_password')->addError('Password do not match');
                $test = false;
            }
        }
        //print_r($_POST['newaccount']);exit;
        
        return $test;
    }

    public function save()
    {
        //register the company
        $c                      = new Model_Company();
        $c->company_name        = $_POST['newaccount']['company_name'];
        $c->username            = $_POST['newaccount']['company_name'];
        $c->mailing_address     = $_POST['newaccount']['company_mail_address'];
        $c->phone               = $_POST['newaccount']['company_phone'];
        $c->website             = $_POST['newaccount']['company_website'];
        if (!empty($_POST['newaccount']['business_category'])) {
            $c->business_category   = new MongoId($_POST['newaccount']['business_category']);
        }
        $c->save();

        $_POST['newaccount']['company_id'] = $c->_id;
        $_POST['newaccount']['password']   = $_POST['personal']['password'];
        $_POST['newaccount']['email']      = $_POST['personal']['email'];
        //$_POST['newaccount']['username']   = $_POST['personal']['username'];
        $_POST['newaccount']['lastname']   = $_POST['personal']['lastname'];
        $_POST['newaccount']['firstname']  = $_POST['personal']['firstname'];
        $_POST['newaccount']['phone']      = $_POST['personal']['phone'];

        //register the user
        $res = $this->_user->register($_POST['newaccount']);
        if (Zend_Registry::isRegistered('loggedin_user')) {
            $user = Zend_Registry::get('loggedin_user');
            $user->type_account = Model_User::COMPANY_ADMIN;
            $user->save();
        }

        //Send the emails
        $subject = Zend_Registry::get('Zend_View')->t('Welcome to Asiaclassified!');
        $message = '';
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        //Post an Ad Registration
        if (!empty($to_be_confirmed_ads->arr)) {
            $user = Zend_Registry::get('loggedin_user');
            Ac_Util::sendEmail($subject, $message, $user->email, true, array('user' => $c, 'listing' => Model_Listing::find($to_be_confirmed_ads->arr[0])), Ac_Mail::TEMPLATE_NEWUSER_POSTANAD);
        }
        //Regular Registration
        else {
            $user = Zend_Registry::get('loggedin_user');
            Ac_Util::sendEmail($subject, $message, $user->email, true, array('user' => $c), Ac_Mail::TEMPLATE_NEWUSER);
        }
        return $res;
    }

    private function getNewSubForm()
    {
        $form = new Ac_SubForm();
        //$form->setDecorators($this->subFormDecorators);
        return $form;
    }
}
